package org.glow.changgou.order.schedule;

import org.glow.changgou.order.pojo.Order;
import org.glow.changgou.order.pojo.OrderItem;
import org.glow.changgou.order.service.OrderService;
import org.glow.changgou.pay.feign.PayFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @Author Glow
 * @Date 2022-10-08 22:04:05
 * @Description 监控Redis的订单队列是否有数据
 * @Version 1.0
 */
@Component
public class TaskService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private PayFeign payFeign;
    @Autowired
    private OrderService orderService;
    @Scheduled(fixedRate = 5000)
    public void task() {
        System.out.println("Thread Name : "
                + Thread.currentThread().getName() + "  i am a task : date ->  "
                + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        //如果订单不为空，则查询微信服务器状态
        if( !redisTemplate.boundHashOps("Order").values().isEmpty())
        {
            //查询微信服务器状态
            //直接拿所有在redis的订单
           Map<String,Order> orders = redisTemplate.boundHashOps("Order").entries();
            for (String orderId: orders.keySet())
            {
                Order order = orders.get(orderId);
                //我就当支付编号了
                Map<String,String> map =(Map<String,String>)payFeign.queryStatus(order.getTransactionId()).getData();
                if (map.get("return_code").equals("SUCCESS"))
                {
                    //交易成功，则修改订单
                   orderService.updateStatus(order.getId(),order.getTransactionId());

                }
                else if(map.get("return_code").equals("FAIL"))
                {
                    orderService.deleteOrder(orderId);
                    order.setPayStatus("0");
                    redisTemplate.boundHashOps("Order").delete(orderId);
                    orderService.update(order);
                }
            }
        }

    }
}
